﻿var hasChecked = false;
//isDouble 如果双击一条数据的时候，就设置为空。这样是为了防止
var isDouble = false;
function setCurrentDate() {
    var curr_time = new Date();
    var strDate = curr_time.getFullYear() + "-";
    strDate += curr_time.getMonth() + 1 + "-";
    strDate += curr_time.getDate() + " ";
    strDate += curr_time.getHours() + ":";
    strDate += curr_time.getMinutes() + ":";
    strDate += curr_time.getSeconds();
    $("#Date").datebox("setValue", strDate);

    var currentDate = curr_time.getFullYear() + "-";
    currentDate += curr_time.getMonth() + 1 + "-";
    currentDate += curr_time.getDate();
    $("#dateto").datebox("setValue", currentDate);

    var before2Yeas = curr_time.getFullYear() - 2 + "-";
    before2Yeas += curr_time.getMonth() + 1 + "-";
    before2Yeas += curr_time.getDate();
    $("#datefrom").datebox("setValue", before2Yeas);

}

function setSearcherItems() {
    url = "../../BusinessTier/Handlers/OtherHanders/GetRequiredFromFile.ashx?type=s";
    $.get(url, function (data) {
        if (data != "-1") {
            var lists = data.split(';');
            for (var i = 0; i < lists.length; i++) {
                var chbInput = document.getElementsByName(lists[i])[0];
                if (chbInput.type == "checkbox") {
                    chbInput.checked = true;
                }
            }
        }
    });
}

$(function () {
    //    setDisabled();
    setCurrentDate();
    setSearcherItems();

    //    $('#ShopName').combobox({
    //        editable: false,
    //        method: 'post',
    //        url: '../Handlers/RegisterHandler/GetShopHandler.ashx'
    //    });

    //    $('#allShops').combobox({
    //        editable: false,
    //        method: 'post',
    //        url: '../Handlers/RegisterHandler/GetShopHandler.ashx',
    //        onLoadSuccess: function () { //加载完成后,设置选中第一项
    //            var val = $(this).combobox("getData");
    //            for (var item in val[0]) {
    //                if (item == "ShopID") {
    //                    $(this).combobox("select", val[0][item]);
    //                }
    //            }
    //        }
    //    });

    //    $('#allUsers').combobox({
    //        editable: false,
    //        method: 'post',
    //        url: '../Handlers/UserHandler/GetUserHandler.ashx',
    //        onLoadSuccess: function () { //加载完成后,设置选中第一项
    //            var val = $(this).combobox("getData");
    //            for (var item in val[0]) {
    //                if (item == "UserID") {
    //                    $(this).combobox("select", val[0][item]);
    //                }
    //            }
    //        }
    //    });
    $('#Register').datagrid({
        title: '登记记录',
        url: '../../BusinessTier/Handlers/RegisterHandler/GetRegisterHandler.ashx',
        singleselect: true,
        method: 'post',
        idField: 'id',
        width: 'auto',
        height: 'auto',
        columns: cols,
        fitCloumns: true,
        nowrap: true,
        pagination: true,
        onBeforeLoad: function (param) {
        },
        onLoadSuccess: function (data) {
            $("#txtTotalCash").val(data.totalMoney);
            $("#txtOrderCount").val("订单：" + data.total);
        },
        onLoadError: function () {
        },
        onClickCell: function (rowIndex, field, value) {
        },
        onDblClickRow: function () {
            isDouble = true;
            var row = $('#Register').datagrid('getSelected');
            if (row) {
                url = "../Handlers/RegisterHandler/UpdateRegisterHandler.ashx?id=" + row.ProID + "&OldQQRelation=" + row.QQRelation;
                $('#newRegisterDlg').dialog('open').dialog('setTitle', '更新');
                $('#fm').form('clear');
                //$("#province").append("<option selected='selected' value='" + row.Province + "'>" + row.Province + "</option>");
                $("#province option[text='" + row.Province + "']").attr("selected", true);
                $("#city").append("<option selected='selected' value='" + row.City + "'>" + row.City + "</option>");
                $("#district").append("<option selected='selected' value='" + row.District + "'>" + row.District + "</option>");
                $("#beizhu").val(row.Beizhu);
                $('#fm').form('load', row);
            }
        }

    });
})

var createGridHeaderContextMenu = function (e, field) {
    e.preventDefault();
    var grid = $(this); /* grid本身 */
    var headerContextMenu = this.headerContextMenu; /* grid上的列头菜单对象 */
    if (!headerContextMenu) {
        var tmenu = $('<div style="width:100px;"></div>').appendTo('body');
        var fields = grid.datagrid('getColumnFields');
        for (var i = 0; i < fields.length; i++) {
            var fildOption = grid.datagrid('getColumnOption', fields[i]);
            if (!fildOption.hidden) {
                $('<div iconCls="icon-ok" field="' + fields[i] + '"/>').html(fildOption.title).appendTo(tmenu);
            } else {
                $('<div iconCls="icon-empty" field="' + fields[i] + '"/>').html(fildOption.title).appendTo(tmenu);
            }
        }
        headerContextMenu = this.headerContextMenu = tmenu.menu({
            onClick: function (item) {
                var field = $(item.target).attr('field');
                if (item.iconCls == 'icon-ok') {
                    grid.datagrid('hideColumn', field);
                    $(this).menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-empty'
                    });
                } else {
                    grid.datagrid('showColumn', field);
                    $(this).menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-ok'
                    });
                }
            }
        });
    }
    headerContextMenu.menu('show', {
        left: e.pageX,
        top: e.pageY
    });
};
$("#Register").datagrid.defaults.onHeaderContextMenu = createGridHeaderContextMenu;


var url;
function newRegister() {

    setRequirField();
    ClearExistVal();
    ResetDate();
    isDouble = false;
    var keyword = $("#keyword").val();
    if ($.trim(keyword) != "") {
        var arry = keyword.split('\n');
        for (var i = 0; i < arry.length; i++) {
            var v = arry[i];
            var infoSplit = v.split(':');
            if (infoSplit.length > 0) {
                v = v.replace(':', '：');
            }
            var Info = v.split('：');
            if (Info.length > 1) {
                AutoFillByKeywords($.trim(Info[0]), $.trim(Info[1]));
            }
        }
        $('#newRegisterDlg').dialog('open').dialog('setTitle', '新增登记');
        url = '../Handlers/RegisterHandler/AddRegisterHandler.ashx';
    }
    else {

        $('#newRegisterDlg').dialog('open').dialog('setTitle', '新增登记');
        url = '../Handlers/RegisterHandler/AddRegisterHandler.ashx';
    }
}

function ResetDate() {
    var curr_time = new Date();
    var strDate = curr_time.getFullYear() + "-";
    strDate += curr_time.getMonth() + 1 + "-";
    strDate += curr_time.getDate() + " ";
    strDate += curr_time.getHours() + ":";
    strDate += curr_time.getMinutes() + ":";
    strDate += curr_time.getSeconds();
    $("#Date").datebox("setValue", strDate);
}

function ClearExistVal() {
    $("#QQ").val("");
    $("#Wangwang").val("");
    $("#ZhifubaoAccount").val("");
    $("#ZhifubaoName").val("");
    $("#RebateZhifubao").val("");
    $("#RebateZhifubaoName").val("");
    $("#CaifutongAccount").val("");
    $("#CaifutongName").val("");
    $("#BankAccount").val("");
    $("#BankName").val("");
    $("#Source").val("");
    $("#Cash").val("");
    $("#Cellphone").val("");
    $("#Fixphone").val("");
    $("#ReceiveName").val("");
    $("#ReceiveAddress").val("");
    $("#ReceiveCellphone").val("");
    $("#ReceiveFixphone").val("");
    $("#beizhu").val("");
    $("#txtQQRelation").val("");
}
function AutoFillByKeywords(field, value) {
    if (field == "QQ") {
        $("#QQ").val(value);
    }
    if (field == "旺旺") {
        $("#Wangwang").val(value);
    }
    if (field == "绑定支付宝账号") {
        $("#ZhifubaoAccount").val(value);
    }
    if (field == "绑定支付宝账号姓名") {
        $("#ZhifubaoName").val(value);

    }
    if (field == "收款支付宝账号") {
        $("#RebateZhifubao").val(value);
    }
    if (field == "收款支付宝账号姓名") {
        $("#RebateZhifubaoName").val(value);
    }
    if (field == "电话") {
        $("#Cellphone").val(value);
    }
    if (field == "银行账号") {
        $("#BankAccount").val(value);
    }
    if (field == "银行户名") {
        $("#BankName").val(value);
    }
    if (field == "何种银行") {
        $("#BankType").val(value);
    }
}

function copyRegister() {
    var row = $('#Register').datagrid('getSelected');
    if (row == null) {
        jQuery.messager.alert('提示:', '请选择一条要登记的记录！');
        return;
    }
    if (row.Wangwang == "" || row.ShopName == "") {
        jQuery.messager.alert('提示:', '该条数据旺旺或者店名为空，不能登记，请完善数据再试！');
        return;
    }
    var u = $("#webCurrentUserName").val();
    url = "../Handlers/RegisterHandler/CopyRegisterHandler.ashx?uWangwang=" + row.Wangwang + "&u=" + u + "&uShopName=" + row.ShopName;
    $('#fm').form('submit', {
        url: url,
        onSubmit: function () {
            //  return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');

            if (!!result.exist) {
                jQuery.messager.alert('提示:', '该数据最近一次的登记日期是：' + result.updatedate + '!');
                return;
            }
            if (result.errorMsg) {
                $.messager.show({
                    title: 'Error',
                    msg: result.errorMsg
                });
            } else {
                jQuery.messager.alert('提示:', '登记成功！');
                $('#newRegisterDlg').dialog('close');        // close the dialog
                $('#Register').datagrid('reload');    // reload the user data
            }
        }
    });
}

function deleteRegister() {
    var row = $('#Register').datagrid('getSelected');
    $("#txtPasswords").val("");
    if (row) {
        document.getElementById("bg2").style.display = "block";
        document.getElementById("myConfirmPasswordDiv").style.display = "block";
    }
    else {
        alert("请选定一条数据，谢谢。");
    }
}

function GetPasswordByUser() {
    var row = $('#Register').datagrid('getSelected');
    var user = document.getElementById("webCurrentUserName").value;
    var pass = document.getElementById("txtPasswords").value;
    if (pass != "") {
        url = "../Handlers/UserHandler/GetPasswordByUserName.ashx?username=" + user + "&password=" + pass + "&id=" + row.ProID;
        $.messager.confirm('确认', '您确定要删除该条记录吗?', function (r) {
            if (r) {
                $.post(url, function (result) {
                    if (result == "success") {
                        var msg = "成功删除 QQ 为[" + row.QQ + "]的数据！";
                        alert(msg);
                        $('#Register').datagrid('reload');    // reload the user data
                    } else {
                        alert("密码不正确，请重试！");
                    }
                });
            }
        });
        document.getElementById("bg2").style.display = 'none';
        document.getElementById("myConfirmPasswordDiv").style.display = 'none';
    }
    else {
        alert("密码不能为空");
    }
}

function setRequirField() {
    url = "../Handlers/OtherHanders/GetRequiredFromFile.ashx?type=r";
    $.get(url, function (data) {
        var allList = data.split(';');
        for (var i = 0; i < allList.length; i++) {
            $("#" + allList[i]).validatebox({
                required: true
            });
        }
    });
}

function saveSearchProjects() {
    var allInputs = document.getElementsByTagName("input");
    var sb = "";
    for (i = 0; i < allInputs.length; i++) {
        if (allInputs[i].checked) {
            sb += allInputs[i].value + ";";
        }
    }
    url = "../Handlers/OtherHanders/HandlerSeacherProjects.ashx?val=" + sb;
    $.get(url, function (data) {
        alert(data);
    });
}

function saveRegister() {
    var isNull = false;
    var qq = $("#QQ").val();
    var shopid = $('#ShopName').combobox('getValue');
    var url2 = "../Handlers/RegisterHandler/RegisterDate.ashx?qq=" + qq + "&shop=" + shopid;
    var isOK;
    $.post(url2, function (data) {
        if (data == "true") {
            isOK = true;
        }
        else {
            isOK = false;
        }
    });
    if (isDouble) {
        RegisterData();
    }
    else {
        if (isOK) {
            $.messager.confirm('警告', '相同QQ+相同店铺十天内已录入一条数据，您仍然要录入该数据吗？?', function (r) {
                if (r) {
                    RegisterData();
                }
            });
        } else {
            RegisterData();
        }
    }
}
function RegisterData() {
    $('#fm').form('submit', {
        url: url,
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');
            if (result.errorMsg) {
                alert(result.errorMsg);
                $.messager.show({
                    title: 'Error',
                    msg: result.errorMsg
                });
            } else {
                alert("你已经成功添加或修改了登记数据！");
                $('#newRegisterDlg').dialog('close');        // close the dialog
                $('#Register').datagrid('reload');    // reload the user data
            }
        }
    });
}

$.ajaxSetup({
    async: false
});

var allSearcherItems = null;
function getSearchProjectFromConfigFile() {
    url = "../Handlers/OtherHanders/GetRequiredFromFile.ashx?type=s";
    $.get(url, function (data) {
        allSearcherItems = data;
    });
}
function Search() {
    getSearchProjectFromConfigFile();
    ReloadGrid();
}


function getscope() {
    var qq = $("#chbqq").val();
    return qq;
}

function ReloadGrid() {

    var keyword = $.trim($("#keyword").val());
    var datefrom = $("#datefrom").datebox("getValue");
    var dateto = $("#dateto").datebox("getValue");
    var pricefrom = $.trim($("#pricefrom").val());
    var priceto = $.trim($("#priceto").val());
    var queryParams = $('#Register').datagrid('options').queryParams;
    var limitdays = $.trim($("#LimitDays").val());
    var shopId = $('#allShops').combobox('getValue');
    var userName = $('#allUsers').combobox('getText');
    if (allSearcherItems != "-1") {
        hasChecked = true;
    }
    else {
        hasChecked = false;
    }

    queryParams.hasChecked = hasChecked;
    queryParams.isSearch = "yes";
    queryParams.keywords = keyword;
    queryParams.datefrom = datefrom;
    queryParams.dateto = dateto;
    queryParams.pricefrom = pricefrom;
    queryParams.priceto = priceto;
    queryParams.limitdays = limitdays;
    queryParams.chkqq = $("#chbQQ").attr("checked") == "checked" ? "1" : "";
    queryParams.chbcaifutong = $("#chbcaifutong").attr("checked") == "checked" ? "1" : ""; ;
    queryParams.chbcaifutongname = $("#chbcaifutongname").attr("checked") == "checked" ? "1" : "";
    queryParams.chbzhifubaoname = $("#chbrebatename").attr("checked") == "checked" ? "1" : "";
    queryParams.chbzhifubaoaccount = $("#chbrebatezhifubao").attr("checked") == "checked" ? "1" : "";
    queryParams.chbfkzhifubaoname = $("#chbfkzhifubaoname").attr("checked") == "checked" ? "1" : "";
    queryParams.chbfkzhifubao = $("#chbfkzhifubao").attr("checked") == "checked" ? "1" : "";
    queryParams.searchScope = allSearcherItems;
    queryParams.shopId = shopId;
    queryParams.userName = userName;
    queryParams.isSourceQuery = document.getElementById("chbSourceQuery").checked;
    if (queryParams.isSourceQuery.toString() == "true" && queryParams.keywords.trim() == "") {
        alert("请在搜索关键字框中输入‘来源’信息");
        return;
    }

    hidediv();
    $('#Register').datagrid('options').queryParams = queryParams;
    $("#Register").datagrid('reload');
}

function showdiv() {
    document.getElementById("bg").style.display = "block";
    document.getElementById("show").style.display = "block";
}
function hidediv() {
    document.getElementById("bg").style.display = 'none';
    document.getElementById("show").style.display = 'none';

    document.getElementById("bg2").style.display = 'none';
    document.getElementById("myConfirmPasswordDiv").style.display = 'none';

}

function importCheck() {
    var file = document.getElementById("fAddress");
    if (file.value == "") {
        jQuery.messager.alert('提示:', '请选择文件！');
        return false;
    }
}


function Import() {
    if (importCheck() == false) {
        return;
    }
    url = "../Handlers/RegisterHandler/ImportRegisterHandler.ashx?filepath=" + document.getElementById("fAddress").value;
    $('#fm').form('submit', {
        url: url,
        onSubmit: function () {
            //  return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');
            if (!!result.exist) {
                jQuery.messager.alert('提示:', '该数据最近一次的登记日期是：' + result.updatedate + '!');
                return;
            }
            if (result.errorMsg) {
                $.messager.show({
                    title: 'Error',
                    msg: result.errorMsg
                });
            } else {
                jQuery.messager.alert('提示:', '登记成功！');
                $('#newRegisterDlg').dialog('close');        // close the dialog
                $('#Register').datagrid('reload');    // reload the user data
            }
        }
    });
}


function importCheck() {
    var file = document.getElementById("fAddress");
    if (file.value == "") {
        jQuery.messager.alert('提示:', '请选择文件！');
        return false;
    }
}
//Set the QQ CheckBox to "True".
function setQQCheckIsTrue() {
    var obj = document.getElementById("chbBankName");
    if (obj.checked) {
        $("#chbQQ").attr("checked", true);
    }
}


$.extend($.fn.validatebox.defaults.rules, {
    Rebatezhifubao: {
        validator: function (value, para) {
            return value.length > 0 || para.length > 0;
        },
        message: '支付宝或者财付通有一项不能为空！'
    }
});